//
//  LocationHelper.m
//  uteped_sdk
//
//  Created by mateng on 2024/4/2.
//

#import "LocationHelper.h"

@interface LocationHelper ()

@property(nonatomic, assign) NSInteger signalLevel;
@property(nonatomic, strong) CLLocation *currentLocation;
@property(nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation LocationHelper

static LocationHelper* instance = nil;

+ (LocationHelper*) shareInstance
{
    if ( instance == nil ) {
        instance = [[LocationHelper alloc] init];
    }
    return instance;
}

- (id)init {
    if (self = [super init]) {
//        [self startLocation];
    }
    
    return self;
}

- (void)startLocation {
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
    }
    
    if (![CLLocationManager locationServicesEnabled]) {
        [self.locationManager requestWhenInUseAuthorization];
        self.locationManager.distanceFilter = 10;
        [self.locationManager startUpdatingLocation];
    }
    else {
        [self.locationManager requestAlwaysAuthorization];
        self.locationManager.distanceFilter = 10;
        [self.locationManager startUpdatingLocation];
    }
}

- (void)stopLocation {
    if (self.locationManager != nil) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = [locations lastObject];
    self.signalLevel = [self getGpsSignalLevel:newLocation];
    self.currentLocation = newLocation;
    NSLog(@"signal level %ld", self.signalLevel);
    if (self.delegate != nil) {
        [self.delegate onSignalLevelChanged:self.signalLevel];
    }
}

- (NSInteger) getGpsSignalLevel:(CLLocation *) location {
    if (location.horizontalAccuracy < 0) {
        return 0;
    }
    else if (location.horizontalAccuracy > 143) {
        return 1;
    }
    else if (location.horizontalAccuracy > 98) {
        return 2;
    }
    else if (location.horizontalAccuracy > 48) {
        return 3;
    }
    else {
        return 4;
    }
}


@end
